package com.example.lifecycle.base;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Checkable;

import java.util.List;

public class FragmentAdapter implements View.OnClickListener {

    public interface OnChangeListener {
        boolean clickBegin(int selectIndex, View view);

        boolean selected(int selectIndex, View view);
    }

    private OnChangeListener listener;

    public void setListener(OnChangeListener listener) {
        this.listener = listener;
    }

    private FragmentActivity fragmentActivity;
    private List<Fragment> fragments;
    private int currentPage = -1;
    private int viewId;
    private List<View> views;


    public FragmentAdapter(FragmentActivity fragmentActivity, List<Fragment> fragments, List<View> views, int currentPage, int viewId) {
        this.fragmentActivity = fragmentActivity;
        this.fragments = fragments;
        this.viewId = viewId;
        this.views = views;
        changeIndex(currentPage);
        setOnClick();
    }

    private FragmentTransaction getFt() {
        return fragmentActivity.getSupportFragmentManager().beginTransaction();
    }

    private void changeIndex(int page) {

        if (page == currentPage) {
            return;
        }

        if (currentPage != -1) {
            Fragment oldFragment = fragments.get(currentPage);
            if (oldFragment.isAdded()) {
                getFt().hide(oldFragment).hide(oldFragment).commitAllowingStateLoss();
                oldFragment.onStop();
                selectView(views.get(currentPage), false);
            }
        }

        Fragment newFragment = fragments.get(page);
        if (newFragment.isAdded()) {
            getFt().show(newFragment).commitAllowingStateLoss();
            newFragment.onResume();
        } else {
            getFt().add(viewId, newFragment).commitAllowingStateLoss();
        }
        selectView(views.get(page), true);
        currentPage = page;
    }


    private void selectView(View view, boolean select) {
        if (view instanceof Checkable) {
            ((Checkable) view).setChecked(select);
        } else {
            view.setSelected(select);
        }
    }


    @Override
    public void onClick(View view) {
        int index = views.indexOf(view);
        if (listener != null) {
            if (listener.clickBegin(index, view)) {
                changeIndex(index);
                listener.selected(index, view);
            }
        } else {
            changeIndex(index);
        }


    }

    public void setOnClick() {
        for (View view : views
                ) {
            view.setOnClickListener(this);
        }
    }
}
